package tutorial.java.swing;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ImageDemo extends JFrame{
	public ImageDemo(){
		setSize(400,300);
		setVisible(true);
		setLocation(500, 250);
		setResizable(false);
		JLabel label = new JLabel();
		add(label);
		label.setSize(350, 200);
		System.out.println("x: " + label.getSize().width + " y: " + label.getSize().height);
		setPicture(label, "vk.jpg");
	
	}
	
	public void setPicture(JLabel label , String fileName){
		try {
			BufferedImage image = ImageIO.read(new File(fileName));
			int x = label.getSize().width;
			int y = label.getSize().height;
			
			int ix = image.getWidth();
			int iy = image.getHeight();
			
			int dx = 0;
			int dy = 0;
			
			if (x/y > ix/iy) {
				dy = y;
				dx = dy * ix/iy;
			} else {
				dx = x;
				dy = dx *  iy/ix;
			}
			
			ImageIcon icon = new ImageIcon(image.getScaledInstance(dx, dy, image.SCALE_SMOOTH));
			label.setIcon(icon);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		ImageDemo imageDemo = new ImageDemo();
		
	}
}
